package com.bootdo.common.task;

import com.bootdo.common.domain.DictDO;
import com.bootdo.common.service.DictService;
import com.bootdo.common.utils.WebSocketUtil;
import com.bootdo.oa.config.WebSocket;
import com.bootdo.system.domain.UserOnline;
import com.bootdo.system.service.SessionService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 锁定解锁任务
 */
@Component
public class UnLockSystemTask implements Job{

    @Autowired
    private DictService dictService;

    @Autowired
    WebSocket webSocket;

    @Autowired
    SessionService sessionService;

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        System.out.println("关闭锁定");

        // 设置锁定状态
        Map<String, Object> map = new HashMap<>(16);
        map.put("type", "lock_status");
        DictDO dictDO = dictService.list(map).get(0);
        dictDO.setName("0");
        dictDO.setValue("0");
        if (dictService.update(dictDO) > 0) {
            try {
                //定时任务
                WebSocketUtil.sendDeviceMessage(webSocket, "2", "系即将强制退出。");
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        // 强制退出
        List<UserOnline> userOnlines = sessionService.list();
        for (UserOnline userOnline : userOnlines) {
            sessionService.forceLogout(userOnline.getId());
        }

    }

}